<template>
  <div class="page" v-if="state.films.length">
    <Banner v-model:activeIndex="state.curIndex" :films="state.films" />

    <WrapTwo
      :film="curFilm"
      :list="state.curList"
      :date="state.curDate"
      @change="onChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, computed, reactive } from "vue";
import { useRoute } from "vue-router";
import useStore from "@/hooks/useStore";
import Banner from "./components/banner.vue";
import WrapTwo from "./components/wrap-two.vue";
import { watch } from "vue";

const { schedule } = useStore();
const route = useRoute();

const state = reactive({
  // 电影列表数据
  films: [] as IFilm[],
  // 当前选中的电影下标
  curIndex: 0,
  // 当前要渲染的场次列表
  curList: [] as ISchedule[],
  // 当前选择的日期
  curDate: 0,
});
// 当前选中的电影
const curFilm = computed(() => state.films[state.curIndex]);

const onChange = (newDate: number) => {
  console.log("onChange", state.curDate !== newDate);
  if (state.curDate !== newDate) {
    state.curDate = newDate;

    getCurList();
  }
};

watch(
  () => state.curIndex,
  (newVal) => {
    // 1. 修改 state.curDate 的值
    state.curDate = state.films[newVal].showDate![0];
    // console.log(state.curDate);
    // 2. 再调用接口
    getCurList();
  }
);

// 获取电影列表数据
async function getFilmList() {
  const resp = await schedule.get(route.params.id as string);
  state.films = resp;
  // 手动使用 state.films[0].showDate[0] 作为初始的 curDate
  state.curDate = resp[0].showDate![0];
}

async function getCurList() {
  const resp = await schedule.getList(
    route.params.id as string,
    curFilm.value.filmId,
    state.curDate
  );
  // 赋值给 curList
  state.curList = resp;
}

onMounted(async () => {
  await getFilmList();

  await getCurList();
});
</script>
